package demo.clone;

import java.io.*;

public class Writer implements Cloneable, Serializable {
    private int age;
    private String name;
    private Book book;

    public Writer() {
    }

    public Writer(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public Writer(int age, String name, Book book) {
        this.age = age;
        this.name = name;
        this.book = book;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Override
    public String toString() {
        String txt = super.toString();
        if (txt != null && txt.length() >= 11) {
            return txt.substring(11) + " {" +
                    " age=" + age +
                    ", name='" + name + '\'' +
                    ", book=" + book +
                    " }";
        } else {
            return "{" +
                    " age=" + age +
                    ", name='" + name + '\'' +
                    ", book=" + book +
                    " }";
        }
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    /**
     * 深度拷贝
     *
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public Object deepClone() throws IOException, ClassNotFoundException {
        // 序列化
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);

        oos.writeObject(this);

        // 反序列化
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);

        return ois.readObject();
    }
}
